#include <malloc.h>
#include <stdlib.h>

#include "mem_hash.h"
#include "log.h"
#include "uthash.h"

struct pointer_statist *hash_find_pointer_statist(struct pointer_statist *head, void *ptr)
{
	log_info("begin hash_find_pointer_statist.");
	if (head == NULL || ptr == NULL) {
		log_warning("head is NULL or ptr is NULL.");
		return NULL;
	}
	struct pointer_statist *ps = NULL;

	HASH_FIND_PTR(head, &ptr, ps);

	return ps;
}

int hash_add_pointer_statist(struct pointer_statist **head, void *ptr, size_t size)
{
	log_info("begin hash_add_pointer_statist.");
	if (head == NULL || ptr == NULL) {
		log_error("head is NULL or ptr is NULL.");
		return -1;
	}

	struct pointer_statist *ps = NULL;

	ps = hash_find_pointer_statist(*head, ptr);
	if (ps != NULL) {
		log_error("ptr already exists in hash table.");
		return -2;
	}

	ps = (struct pointer_statist *)malloc(sizeof(struct pointer_statist));
	if (ps == NULL) {
		log_error("No enough mem.");
		return -3;
	}

	ps->ptr = ptr;
	ps->size = (unsigned long)size;

	HASH_ADD_PTR(*head, ptr, ps);

	return 0;
}

int hash_delete_pointer_statist(struct pointer_statist **head, struct pointer_statist *ps)
{
	log_info("being hash_delete_pointer_statist.");
	if (head == NULL) {
		log_error("head is NULL.");
		return -1;
	}

	if (ps == NULL) {
		log_warning("ps is NULL.");
		return 0;
	}
	
	HASH_DEL(*head, ps);

	return 0;
}
